#include <iostream>
#include <vector>
#include <queue>
using namespace std;

class Solution {
    public:
	vector<int> loudAndRich(vector<vector<int>> &richer, vector<int> &quiet)
	{
                int n = quiet.size();
                vector<vector<int>> gh(n);
                vector<int> degree(n, 0);
                vector<int> ans(n);
                for(auto e : richer){
                        gh[e[0]].push_back(e[1]);
                        degree[e[1]]++;
                }

                queue<int> q;
                for(int i = 0; i < n; i++){
                        if(degree[i] == 0){
                                q.push(i);
                        }
                        ans[i] = i;
                }

                while(!q.empty()){
                        int u = q.front();
                        q.pop();
                        for(auto v : gh[u]){
                                if(quiet[ans[u]] < quiet[ans[v]]){
                                        ans[v] = ans[u];
                                }
                                if(--degree[v] == 0){
                                        q.push(v);
                                }
                        }
                }

                return ans;
	}
};

int main()
{
        vector<vector<int>> richer = {{1,0},{2,1},{3,1},{3,7},{4,3},{5,3},{6,3}};
        vector<int> quiet = {3,2,5,4,6,1,7,0};
        vector<int> ans = Solution().loudAndRich(richer, quiet);
        for(auto v : ans){
                cout << v << " ";
        }
        cout<<endl;
        return 0;
}
